const router = require('koa-router')()
const uploader = require('../uploader')
const mongoose = require('mongoose');
const path = require('path');
const util = require('util');
const fs = require('fs')
const rename = util.promisify(fs.rename)
const stats = require('../helpers/stats')
const popular = require('../helpers/popular')
const latestComments = require('../helpers/comments')
const comments = require('./comments');
const checkToken = require('../helpers/checkToken')

router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')
const moment = require('moment');

router.post('/',uploader.single('file'),async function (ctx, next) {
    let file = ctx.req.file;
    if(!file){
        return ctx.redirect('/?message=%u4f60%u6ca1%u6709%u9009%u62e9%u56fe%u7247%u554a%uff01');
    }
    let diskFilename = file.filename + path.extname(file.originalname)
    await rename(file.path , path.join(path.dirname(file.path) , diskFilename))
        .then(() => Image.create({
            title: ctx.req.body.title,
            description: ctx.req.body.description,
            filename: diskFilename,
            originalname: ctx.req.file.originalname,
            mimetype: ctx.req.file.mimetype
        })
    )
    .then(doc => ctx.redirect(`/images/${doc.id}`))
    .catch(err => ctx.throw(500, err))
})

router.get('/:id',async (ctx,next) => {
    var token = ctx.cookies.get('token')
    let imageId = ctx.params.id
    await Image.findByIdAndUpdate(imageId,{$inc:{views:1}})
    .then(() => Promise.all([
            Image.findById(imageId),
            stats(),
            Comment.find({image: imageId}).sort({timestamp : -1}),
            popular(),
            latestComments(),
            checkToken(token)
        ])
    )
    .then( ([image ,stats ,comments ,popular ,latestComments,loginAbout]) => {
        if(!image){
            return ctx.redirect(`/`)
        }
        return ctx.render('image', {
            image : image ,
            stats: stats,
            comments: comments,
            popular: popular,
            latestComments:latestComments,
            loginAbout:loginAbout
        })

    })
    .catch(err => ctx.throw(500, err))
})

router.post('/:id/like',async ctx => {
    let imageId = ctx.params.id
    await Image.findByIdAndUpdate(imageId,{$inc:{likes:1}})
    .then(() => Image.findById(imageId))
    .then(image => {
        ctx.body = {likes : image.likes}
    })
    .catch(err => ctx.throw(500, err))
})

router.del('/:id', async ctx => {
    let imageId = ctx.params.id
    await Image.findByIdAndRemove(imageId)
    .then(() => Comment.remove({image:imageId}))
    .then(() => ctx.body = {ok : 1})
    .catch(err => ctx.throw(500, err))
})

router.use('/:imageid/comment', comments.routes(), comments.allowedMethods())

module.exports = router
